import { camera, scene, renderer } from './utils/init2d'
import * as THREE from 'three'
import gsap from 'gsap'
import { CSS2DObject } from 'three/addons/renderers/CSS2DRenderer.js'
import { guiMove } from './utils/gui'
// 创建2d物体
let mesh,helper
function initBase() {
  const geometry = new THREE.PlaneGeometry(10, 10)
  const meterial = new THREE.MeshStandardMaterial({color: 0xffffff})
  const plane = new THREE.Mesh(geometry, meterial)
  plane.rotation.set(-Math.PI / 2, 0, 0)
  plane.receiveShadow = true
  scene.add(plane)
}


function createLight () {
  const directionalLight = new THREE.DirectionalLight(0xffffff, 1)
  directionalLight.position.set(3, 3, 3)
  scene.add(directionalLight)
  directionalLight.castShadow = true
  directionalLight.target = mesh
  helper = new THREE.DirectionalLightHelper(directionalLight, 1)
  scene.add(helper)
}

function createSphere (){
  const sphere = new THREE.SphereGeometry(1, 32, 16)
  const material = new THREE.MeshStandardMaterial( { color: 0x00ff00 } )
  mesh = new THREE.Mesh(sphere, material)
  mesh.position.set(0, 1, 0)
  mesh.castShadow = true
  scene.add(mesh)
}
camera.position.set(5, 5, 5)

function initAnimation () {
  let moveObj = gsap.to(mesh.position, {
    x: 5,
    duration: 1, 
    delay: 2, 
    repeat: -1, 
    yoyo: true, 
    ease: 'sine.out', 
    onStart () {
      console.log('开始了');
    },
    onUpdate () {
      console.log('更新了');
      // 在动画更新的时候更新辅助对象
      helper.update()
    },
    onComplete () {
      console.log('结束了');
    }
  })
  
  window.addEventListener('dblclick', () => {
    if (moveObj.isActive()) {
      moveObj.pause()
    } else {
      moveObj.resume()
    }
  })
}

function create2d() {
  // 2d的文字
  const div = document.createElement('div')
  div.innerHTML = '球体'
  div.style.color = 'red'
  div.style.fontSize = '32px'
  // 2d对象的创建
  const object2d = new CSS2DObject(div)
  object2d.position.set(0, 3, 0)
  // object2d已经是一个3d物体，加入到场景中
  guiMove(object2d)
  scene.add(object2d)
}


renderer.shadowMap.enabled = true
initBase()
createSphere()
createLight()
// initAnimation()
create2d()